<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use app\admin\model\Image;
use app\admin\model\Povertypolicy;
use app\admin\model\Villages;

use think\Db;
use think\Exception;
use think\Request;

class Povertypolicyledger extends Base
{

    public function _initialize() {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
//            $columns = $param['order'][0]['column'];
//            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];
            $order = 'villageId ASC, year DESC';

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($where, $this->defaultWhere);
            }

            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            foreach ($list as $item) {
                $item->villageName = Villages::where(['id' => $item['villageId']])->value('name');
                // 享受政策（项）
                $item->countPovertypolicy = count(json_decode($item['policy'], true));
                $povertypolicyList = Povertypolicy::where(['policyledgerId' => $item['id']])->field('policy')->select();
                // 享受家庭数
                $item->countFamily = Povertypolicy::where(['policyledgerId' => $item['id']])->group('householderId')->count();
                // 享受人数
                $item->countPeople = count($povertypolicyList);
                // 金额合计（元）
                $totalAmount = 0;
                if($povertypolicyList){
                    foreach ($povertypolicyList as $povertypolicy) {
                        $policyList = json_decode($povertypolicy['policy'], true);
                        foreach ($policyList as $policy) {
                            if(count($policy['policySpec']) > 1){
                                // 多列
                                foreach($policy['policySpec'] as $policySpec){
                                    if($policySpec['explain'] == 1 && $policySpec['explainValue']){
                                        $totalAmount += $policySpec['explainValue'];
                                    }
                                }
                            }else{
                                // 一列
                                $policySpec = $policy['policySpec'][0];
                                if($policySpec['explain'] == 1 && $policySpec['explainValue']){
                                    $totalAmount += $policySpec['explainValue'];
                                }
                            }
                        }
                    }
                }

                $item->totalAmount = $totalAmount;
            }
            $count = $model->where($where)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return parent::index();
    }

    public function add(Request $request) {
        // 享受政策
        $policyTypes = get_policys();

        $this->assign('policyTypes', $policyTypes);

        return parent::add($request);
    }

    public function savePost(Request $request, $redirect = '') {
        $model = model($this->model);
        if ($request->isPost()) {
            $data = $request->param();

            try {
                Db::startTrans();

                // 是否已添加了该年度台账
                $where = [
                    'villageId' => $data['villageId'],
                    'year' => $data['year']
                ];
                if(isset($data['id']) && $data['id']){
                    $where['id'] = ['neq', $data['id']];
                }
                $info = $model->where($where)->find();
                if($info){
                    return $this->error('已添加了该年度台账！');
                }

                $policyType = (Array)$data['policyType'];
                $policy = [];
                foreach ($policyType as $key => $value) {
                    $specType = isset($data["specType_$key"]) ? (Array)$data["specType_$key"] : [];
                    $quarter = isset($data["quarter_$key"]) ? (Array)$data["quarter_$key"] : [];
                    $month = isset($data["month_$key"]) ? (Array)$data["month_$key"] : [];
                    $explain = isset($data["explain_$key"]) ? (Array)$data["explain_$key"] : [];
                    // 享受政策规格
                    $policySpec = [];
                    foreach ($specType as $ke => $val) {
                        $policySpec[] = [
                            'specType' => $val,
                            'quarter' => isset($quarter[$ke]) ? $quarter[$ke] : '',
                            'month' => isset($month[$ke]) ? $month[$ke] : '',
                            'explain' => isset($explain[$ke]) ? $explain[$ke] : '',
                        ];
                    }

                    $policy[] = [
                        'policyType' => $value,
                        'policySpec' => $policySpec
                    ];
                }
                $data['policy'] = json_encode($policy);

                if (isset($data['id']) && $data['id']) {
                    // 是否已添加了明细 TODO
                    $povertypolicys = Povertypolicy::where(['policyledgerId' => $data['id']])->count();
                    if($povertypolicys){
                        return $this->error('该台账已添加过明细，不能再次修改！');
                    }

                    $data['updateDate'] = time();
                    $data['updateOper'] = $this->admin->id;

                    $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                    if($result !== false) {
                        // Query执行后的操作
                        $model->_after_update($data);

                        // 写入日志
                        $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                        Common::adminLog($request, $logInfo);

                        Db::commit();
                        return $this->success('保存成功！', 'admin/' . strtolower($this->model) . '/index');
                    } else {
                        Db::rollback();
                        return $this->error($model->getError());
                    }
                } else {
                    $data['id'] = Helper::getUUID();
                    $data['createDate'] = time();
                    $data['createOper'] = $this->admin->id;

                    $result = $model->save($data);

                    if($result !== false) {
                        // Query执行后的操作
                        $model->_after_insert($data);

                        // 写入日志
                        $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                        Common::adminLog($request, $logInfo);

                        Db::commit();
                        return $this->success('添加成功！', 'admin/' . strtolower($this->model) . '/index');
                    } else {
                        Db::rollback();
                        return $this->error($model->getError());
                    }
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
        } else {
            return $this->error('请求方式错误！');
        }
    }

    public function edit(Request $request) {
        // 享受政策
        $policyTypes = get_policys();

        $this->assign('policyTypes', $policyTypes);

        return parent::edit($request);
    }

    public function editPost(Request $request, $redirect = ''){

        return parent::editPost($request, $redirect);
    }

    /**
     * Delete
     */
    public function delete(){
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');

        // 是否已添加了明细
        $povertypolicys = Povertypolicy::where(['policyledgerId' => $id])->count();
        if($povertypolicys){
            return $this->error('该台账已添加过明细，不能删除！');
        }

        if($id){
            $povertypolicy = Povertypolicy::where(['policyledgerId' => $id])->select();
            if($povertypolicy) {
                return $this->error('该台账有政策享受，请先去删除政策享受！');
            }

            Db::startTrans();
            try{
                $result = $model->where('id', $id)->delete();
                if($result !== false){
                    // Query执行后的操作
                    $model->_after_delete($id);

                    $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['cityId']) && $filter['cityId']){
                $where['cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['villageId'] = $filter['villageId'];
            }

            if(isset($filter['title']) && $filter['title']){
                $where['title'] = ['like', '%'.$filter['title'].'%'];
            }
        }

        return $where;
    }

}
